{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据下载\n",
    "\n",
    "Inception-v3模型：[点击下载](https://www.lanzous.com/i5mxw5c)\n",
    "\n",
    "flower_photos数据集：[点击下载](http://download.tensorflow.org/example_images/flower_photos.tgz)\n",
    "\n",
    "解压放到images目录下面，路径参考下面程序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob\n",
    "import os.path\n",
    "import random\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow.python.platform import gfile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Inception-v3模型瓶颈层的节点个数\n",
    "BOTTLENECK_TENSOR_SIZE = 2048\n",
    "\n",
    "# Inception-v3模型中代表瓶颈层结果的张量名称。\n",
    "# 在谷歌提出的Inception-v3模型中，这个张量名称就是'pool_3/_reshape:0'。\n",
    "# 在训练模型时，可以通过tensor.name来获取张量的名称。\n",
    "BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'\n",
    "\n",
    "# 图像输入张量所对应的名称。\n",
    "JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'\n",
    "\n",
    "# 下载的谷歌训练好的Inception-v3模型文件目录\n",
    "MODEL_DIR = './images/model/'\n",
    "\n",
    "# 下载的谷歌训练好的Inception-v3模型文件名\n",
    "MODEL_FILE = 'tensorflow_inception_graph.pb'\n",
    "\n",
    "# 因为一个训练数据会被使用多次，所以可以将原始图像通过Inception-v3模型计算得到的特征向量保存在文件中，免去重复的计算。\n",
    "# 下面的变量定义了这些文件的存放地址。\n",
    "CACHE_DIR = './images/tmp/bottleneck/'\n",
    "\n",
    "# 图片数据文件夹。\n",
    "# 在这个文件夹中每一个子文件夹代表一个需要区分的类别，每个子文件夹中存放了对应类别的图片。\n",
    "INPUT_DATA = './images/flower_photos/'\n",
    "\n",
    "# 验证的数据百分比\n",
    "VALIDATION_PERCENTAGE = 10\n",
    "# 测试的数据百分比\n",
    "TEST_PERCENTAGE = 10\n",
    "\n",
    "# 定义神经网络的设置\n",
    "LEARNING_RATE = 0.01\n",
    "STEPS = 4000\n",
    "BATCH = 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数从数据文件夹中读取所有的图片列表并按训练、验证、测试数据分开。\n",
    "# testing_percentage和validation_percentage参数指定了测试数据集和验证数据集的大小。\n",
    "def create_image_lists(testing_percentage, validation_percentage):\n",
    "    # 得到的所有图片都存在result这个字典(dictionary)里。\n",
    "    # 这个字典的key为类别的名称，value也是一个字典，字典里存储了所有的图片名称。\n",
    "    result = {}\n",
    "    # 获取当前目录下所有的子目录\n",
    "    sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]\n",
    "    # 得到的第一个目录是当前目录，不需要考虑\n",
    "    is_root_dir = True\n",
    "    for sub_dir in sub_dirs:\n",
    "        if is_root_dir:\n",
    "            is_root_dir = False\n",
    "            continue\n",
    "\n",
    "        # 获取当前目录下所有的有效图片文件。\n",
    "        extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']\n",
    "        file_list = []\n",
    "        dir_name = os.path.basename(sub_dir)\n",
    "        for extension in extensions:\n",
    "            file_glob = os.path.join(INPUT_DATA, dir_name, '*.'+extension)\n",
    "            file_list.extend(glob.glob(file_glob))\n",
    "        if not file_list:\n",
    "            continue\n",
    "\n",
    "        # 通过目录名获取类别的名称。\n",
    "        label_name = dir_name.lower()\n",
    "        # 初始化当前类别的训练数据集、测试数据集和验证数据集\n",
    "        training_images = []\n",
    "        testing_images = []\n",
    "        validation_images = []\n",
    "        for file_name in file_list:\n",
    "            base_name = os.path.basename(file_name)\n",
    "            # 随机将数据分到训练数据集、测试数据集和验证数据集。\n",
    "            chance = np.random.randint(100)\n",
    "            if chance < validation_percentage:\n",
    "                validation_images.append(base_name)\n",
    "            elif chance < (testing_percentage + validation_percentage):\n",
    "                testing_images.append(base_name)\n",
    "            else:\n",
    "                training_images.append(base_name)\n",
    "\n",
    "        # 将当前类别的数据放入结果字典。\n",
    "        result[label_name] = {\n",
    "            'dir': dir_name,\n",
    "            'training': training_images,\n",
    "            'testing': testing_images,\n",
    "            'validation': validation_images\n",
    "            }\n",
    "    # 返回整理好的所有数据\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数通过类别名称、所属数据集和图片编号获取一张图片的地址。\n",
    "# image_lists参数给出了所有图片信息。\n",
    "# image_dir参数给出了根目录。存放图片数据的根目录和存放图片特征向量的根目录地址不同。\n",
    "# label_name参数给定了类别的名称。\n",
    "# index参数给定了需要获取的图片的编号。\n",
    "# category参数指定了需要获取的图片是在训练数据集、测试数据集还是验证数据集。\n",
    "def get_image_path(image_lists, image_dir, label_name, index, category):\n",
    "    # 获取给定类别中所有图片的信息。\n",
    "    label_lists = image_lists[label_name]\n",
    "    # 根据所属数据集的名称获取集合中的全部图片信息。\n",
    "    category_list = label_lists[category]\n",
    "    mod_index = index % len(category_list)\n",
    "    # 获取图片的文件名。\n",
    "    base_name = category_list[mod_index]\n",
    "    sub_dir = label_lists['dir']\n",
    "    # 最终的地址为数据根目录的地址 + 类别的文件夹 + 图片的名称\n",
    "    full_path = os.path.join(image_dir, sub_dir, base_name)\n",
    "    return full_path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数通过类别名称、所属数据集和图片编号获取经过Inception-v3模型处理之后的特征向量文件地址。\n",
    "def get_bottlenect_path(image_lists, label_name, index, category):\n",
    "    return get_image_path(image_lists, CACHE_DIR, label_name, index, category) + '.txt';"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数使用加载的训练好的Inception-v3模型处理一张图片，得到这个图片的特征向量。\n",
    "def run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor):\n",
    "    # 这个过程实际上就是将当前图片作为输入计算瓶颈张量的值。这个瓶颈张量的值就是这张图片的新的特征向量。\n",
    "    bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data})\n",
    "    # 经过卷积神经网络处理的结果是一个四维数组，需要将这个结果压缩成一个特征向量（一维数组）\n",
    "    bottleneck_values = np.squeeze(bottleneck_values)\n",
    "    return bottleneck_values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数获取一张图片经过Inception-v3模型处理之后的特征向量。\n",
    "# 这个函数会先试图寻找已经计算且保存下来的特征向量，如果找不到则先计算这个特征向量，然后保存到文件。\n",
    "def get_or_create_bottleneck(sess, image_lists, label_name, index, category, jpeg_data_tensor, bottleneck_tensor):\n",
    "    # 获取一张图片对应的特征向量文件的路径。\n",
    "    label_lists = image_lists[label_name]\n",
    "    sub_dir = label_lists['dir']\n",
    "    sub_dir_path = os.path.join(CACHE_DIR, sub_dir)\n",
    "    if not os.path.exists(sub_dir_path):\n",
    "        os.makedirs(sub_dir_path)\n",
    "    bottleneck_path = get_bottlenect_path(image_lists, label_name, index, category)\n",
    "    # 如果这个特征向量文件不存在，则通过Inception-v3模型来计算特征向量，并将计算的结果存入文件。\n",
    "    if not os.path.exists(bottleneck_path):\n",
    "        # 获取原始的图片路径\n",
    "        image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category)\n",
    "        # 获取图片内容。\n",
    "        image_data = gfile.FastGFile(image_path, 'rb').read()\n",
    "        # print(len(image_data))\n",
    "        # 由于输入的图片大小不一致，此处得到的image_data大小也不一致（已验证），但却都能通过加载的inception-v3模型生成一个2048的特征向量。具体原理不详。\n",
    "        # 通过Inception-v3模型计算特征向量\n",
    "        bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)\n",
    "        # 将计算得到的特征向量存入文件\n",
    "        bottleneck_string = ','.join(str(x) for x in bottleneck_values)\n",
    "        with open(bottleneck_path, 'w') as bottleneck_file:\n",
    "            bottleneck_file.write(bottleneck_string)\n",
    "    else:\n",
    "        # 直接从文件中获取图片相应的特征向量。\n",
    "        with open(bottleneck_path, 'r') as bottleneck_file:\n",
    "            bottleneck_string = bottleneck_file.read()\n",
    "        bottleneck_values = [float(x) for x in bottleneck_string.split(',')]\n",
    "    # 返回得到的特征向量\n",
    "    return bottleneck_values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数随机获取一个batch的图片作为训练数据。\n",
    "def get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category,\n",
    "                                  jpeg_data_tensor, bottleneck_tensor):\n",
    "    bottlenecks = []\n",
    "    ground_truths = []\n",
    "    for _ in range(how_many):\n",
    "        # 随机一个类别和图片的编号加入当前的训练数据。\n",
    "        label_index = random.randrange(n_classes)\n",
    "        label_name = list(image_lists.keys())[label_index]\n",
    "        image_index = random.randrange(65536)\n",
    "        bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, image_index, category,\n",
    "                                              jpeg_data_tensor, bottleneck_tensor)\n",
    "        ground_truth = np.zeros(n_classes, dtype=np.float32)\n",
    "        ground_truth[label_index] = 1.0\n",
    "        bottlenecks.append(bottleneck)\n",
    "        ground_truths.append(ground_truth)\n",
    "    return bottlenecks, ground_truths"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个函数获取全部的测试数据。在最终测试的时候需要在所有的测试数据上计算正确率。\n",
    "def get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):\n",
    "    bottlenecks = []\n",
    "    ground_truths = []\n",
    "    label_name_list = list(image_lists.keys())\n",
    "    # 枚举所有的类别和每个类别中的测试图片。\n",
    "    for label_index, label_name in enumerate(label_name_list):\n",
    "        category = 'testing'\n",
    "        for index, unused_base_name in enumerate(image_lists[label_name][category]):\n",
    "            # 通过Inception-v3模型计算图片对应的特征向量，并将其加入最终数据的列表。\n",
    "            bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,\n",
    "                                                  jpeg_data_tensor, bottleneck_tensor)\n",
    "            ground_truth = np.zeros(n_classes, dtype = np.float32)\n",
    "            ground_truth[label_index] = 1.0\n",
    "            bottlenecks.append(bottleneck)\n",
    "            ground_truths.append(ground_truth)\n",
    "    return bottlenecks, ground_truths"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def main(_):\n",
    "    # 读取所有图片。\n",
    "    image_lists = create_image_lists(TEST_PERCENTAGE, VALIDATION_PERCENTAGE)\n",
    "    n_classes = len(image_lists.keys())\n",
    "    # 读取已经训练好的Inception-v3模型。\n",
    "    # 谷歌训练好的模型保存在了GraphDef Protocol Buffer中，里面保存了每一个节点取值的计算方法以及变量的取值。\n",
    "    # TensorFlow模型持久化的问题在第5章中有详细的介绍。\n",
    "    with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:\n",
    "        graph_def = tf.GraphDef()\n",
    "        graph_def.ParseFromString(f.read())\n",
    "    # 加载读取的Inception-v3模型，并返回数据输入所对应的张量以及计算瓶颈层结果所对应的张量。\n",
    "    bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(graph_def, return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])\n",
    "    # 定义新的神经网络输入，这个输入就是新的图片经过Inception-v3模型前向传播到达瓶颈层时的结点取值。\n",
    "    # 可以将这个过程类似的理解为一种特征提取。\n",
    "    bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECK_TENSOR_SIZE], name='BottleneckInputPlaceholder')\n",
    "    # 定义新的标准答案输入\n",
    "    ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')\n",
    "    # 定义一层全连接层来解决新的图片分类问题。\n",
    "    # 因为训练好的Inception-v3模型已经将原始的图片抽象为了更加容易分类的特征向量了，所以不需要再训练那么复杂的神经网络来完成这个新的分类任务。\n",
    "    with tf.name_scope('final_training_ops'):\n",
    "        weights = tf.Variable(tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, n_classes], stddev=0.001))\n",
    "        biases = tf.Variable(tf.zeros([n_classes]))\n",
    "        logits = tf.matmul(bottleneck_input, weights) + biases\n",
    "        final_tensor = tf.nn.softmax(logits)\n",
    "    # 定义交叉熵损失函数\n",
    "    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input)\n",
    "    cross_entropy_mean = tf.reduce_mean(cross_entropy)\n",
    "    train_step = tf.compat.v1.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean)\n",
    "    # 计算正确率\n",
    "    with tf.name_scope('evaluation'):\n",
    "        correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))\n",
    "        evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "    with tf.Session() as sess:\n",
    "        tf.global_variables_initializer().run()\n",
    "        # 训练过程\n",
    "        for i in range(STEPS):\n",
    "            # 每次获取一个batch的训练数据\n",
    "            train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks(\n",
    "                sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor)\n",
    "            sess.run(train_step, feed_dict={bottleneck_input: train_bottlenecks, ground_truth_input: train_ground_truth})\n",
    "            # 在验证集上测试正确率。\n",
    "            if i%100 == 0 or i+1 == STEPS:\n",
    "                validation_bottlenecks, validation_ground_truth = get_random_cached_bottlenecks(\n",
    "                    sess, n_classes, image_lists, BATCH, 'validation', jpeg_data_tensor, bottleneck_tensor)\n",
    "                validation_accuracy = sess.run(evaluation_step, feed_dict={\n",
    "                    bottleneck_input:validation_bottlenecks, ground_truth_input: validation_ground_truth})\n",
    "                print('Step %d: Validation accuracy on random sampled %d examples = %.1f%%'\n",
    "                      % (i, BATCH, validation_accuracy*100))\n",
    "        # 在最后的测试数据上测试正确率\n",
    "        test_bottlenecks, test_ground_truth = get_test_bottlenecks(sess, image_lists, n_classes,\n",
    "                                                                       jpeg_data_tensor, bottleneck_tensor)\n",
    "        test_accuracy = sess.run(evaluation_step, feed_dict={bottleneck_input: test_bottlenecks,\n",
    "                                                                 ground_truth_input: test_ground_truth})\n",
    "        print('Final test accuracy = %.1f%%' % (test_accuracy * 100))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 开始运行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Logging before flag parsing goes to stderr.\n",
      "W0818 10:06:49.402768 140018601760576 module_wrapper.py:136] From /usr/local/python3/lib/python3.6/site-packages/tensorflow_core/python/util/module_wrapper.py:163: The name tf.app.run is deprecated. Please use tf.compat.v1.app.run instead.\n",
      "\n",
      "W0818 10:06:49.440685 140018601760576 deprecation.py:323] From <ipython-input-10-6359a469440b>:8: FastGFile.__init__ (from tensorflow.python.platform.gfile) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.gfile.GFile.\n",
      "W0818 10:06:49.441340 140018601760576 module_wrapper.py:136] From /usr/local/python3/lib/python3.6/site-packages/tensorflow_core/python/util/module_wrapper.py:163: The name tf.GraphDef is deprecated. Please use tf.compat.v1.GraphDef instead.\n",
      "\n",
      "W0818 10:06:49.918245 140018601760576 deprecation.py:323] From <ipython-input-10-6359a469440b>:26: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 0: Validation accuracy on random sampled 100 examples = 48.0%\n",
      "Step 100: Validation accuracy on random sampled 100 examples = 76.0%\n",
      "Step 200: Validation accuracy on random sampled 100 examples = 85.0%\n",
      "Step 300: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 400: Validation accuracy on random sampled 100 examples = 86.0%\n",
      "Step 500: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 600: Validation accuracy on random sampled 100 examples = 86.0%\n",
      "Step 700: Validation accuracy on random sampled 100 examples = 89.0%\n",
      "Step 800: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 900: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 1000: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 1100: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 1200: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 1300: Validation accuracy on random sampled 100 examples = 89.0%\n",
      "Step 1400: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 1500: Validation accuracy on random sampled 100 examples = 89.0%\n",
      "Step 1600: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 1700: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 1800: Validation accuracy on random sampled 100 examples = 88.0%\n",
      "Step 1900: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 2000: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 2100: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 2200: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 2300: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 2400: Validation accuracy on random sampled 100 examples = 93.0%\n",
      "Step 2500: Validation accuracy on random sampled 100 examples = 86.0%\n",
      "Step 2600: Validation accuracy on random sampled 100 examples = 96.0%\n",
      "Step 2700: Validation accuracy on random sampled 100 examples = 94.0%\n",
      "Step 2800: Validation accuracy on random sampled 100 examples = 81.0%\n",
      "Step 2900: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 3000: Validation accuracy on random sampled 100 examples = 87.0%\n",
      "Step 3100: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 3200: Validation accuracy on random sampled 100 examples = 92.0%\n",
      "Step 3300: Validation accuracy on random sampled 100 examples = 86.0%\n",
      "Step 3400: Validation accuracy on random sampled 100 examples = 87.0%\n",
      "Step 3500: Validation accuracy on random sampled 100 examples = 94.0%\n",
      "Step 3600: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 3700: Validation accuracy on random sampled 100 examples = 95.0%\n",
      "Step 3800: Validation accuracy on random sampled 100 examples = 90.0%\n",
      "Step 3900: Validation accuracy on random sampled 100 examples = 91.0%\n",
      "Step 3999: Validation accuracy on random sampled 100 examples = 85.0%\n",
      "Final test accuracy = 91.2%\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[0;31mSystemExit\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py:3333: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.\n",
      "  warn(\"To exit: use 'exit', 'quit', or Ctrl-D.\", stacklevel=1)\n"
     ]
    }
   ],
   "source": [
    "tf.app.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
